package net.shop.biz.service;

import java.io.StringWriter;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import ths.web.spring.BeansManager;
import ths.web.template.TemplateEngineException;

@Service
public class MailSenderService {
	
	@Resource
	private JavaMailSender javaMailSender;
	
	@Resource
	private TaskExecutor taskExecutor;
	
	// 增加邮件发送任务
	public void addSendMailTask(final MimeMessage mimeMessage) {
		try {
			taskExecutor.execute(new Runnable() {
				public void run(){
					javaMailSender.send(mimeMessage);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendMail(String subject, String body, String toMail) {
		try {

	        String username = "programlife555";
	        String password = "1234";

			//String from = "神州商城  <programlife555@163.com>";
			String from = "programlife555@163.com";
			JavaMailSenderImpl javaMailSenderImpl = (JavaMailSenderImpl)javaMailSender;
			javaMailSenderImpl.setUsername(username);
			javaMailSenderImpl.setPassword(password);
			MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();

			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
			mimeMessageHelper.setFrom(MimeUtility.encodeWord(from));
			mimeMessageHelper.setTo(toMail);
			
			//1 高优先级. 有些邮件程序称之为紧急 2 也是高优先级 3 普通优先级 4 低优先级 5 最低的优先级	
			mimeMessageHelper.setPriority(1);
			mimeMessageHelper.setSubject(subject);
			mimeMessageHelper.setText(body, true);
				
			javaMailSender.send(mimeMessage);
			//addSendMailTask(mimeMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendPasswordRecoverMail() {
		
		StringWriter writer = new StringWriter();
		HashMap<String, Object> mailContext = new HashMap<String, Object>();
		String resource = BeansManager.getFrontController().getViewResourceFullPath("mail/password_recover");
		
		try {
			BeansManager.getTemplateEngine().render(resource, mailContext, writer);
		} catch (TemplateEngineException e) {
			e.printStackTrace();
		}
		
		String subject = "神州商城账户激活邮件";
		sendMail(subject, writer.toString(), "tianhaisheng555@163.com");
	}	
}
